package com.tzinfo.tzb;

import java.io.File;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.domain.ClassList.ClassData.ClassSubMenu;
import com.tzinfo.tzb.domain.DiaryList.DiaryData.DiaryPhoto;
import com.tzinfo.tzb.domain.DefaultResult;
import com.tzinfo.tzb.domain.Tzb_UserInfoModel;
import com.tzinfo.tzb.util.FileConfig;
import com.tzinfo.tzb.util.HttpTools;
import com.tzinfo.tzb.util.TzbCommonData;
import com.tzinfo.tzt.R;
import com.yxw.util.OutLog;
import com.yxw.view.util.ResFinder;

public class TzbBangFatieActivity extends TzbBaseActivity {

	public static TzbBangFatieActivity activity;
	// 标志
	public static int tabNo;

	// 参数
	private ClassSubMenu classSubMenu = null;
	private int fid = -1, tid = -1;
	private String pid = null;
	private String stitle = null;

	// UI组件
	private ImageView image_theme_title, img_touxiang, img_tiezi_tupian,
			img_delete;
	private TextView text_title;
	private TextView text_theme_title;
	private TextView text_tiezi_title;
	private TextView text_tiezi_context;
	private AlertDialog dlg;

	// 数据
	DefaultResult result = null;
	private Object imagePath = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tzb_ac_main_bang_fatie);
		activity = this;
		initParameter();
		init();
		initUserInfo();
	}

	private void initParameter() {
		classSubMenu = TzbCommonData.classSubMenu;
		Intent thisIntent = this.getIntent();
		fid = thisIntent.getIntExtra("fid", -1);
		tid = thisIntent.getIntExtra("tid", -1);
		stitle = thisIntent.getStringExtra("stitle");
	}

	private void init() {
		// 加载滚动进入条
		mProgressBar = (ProgressBar) ResFinder.findViewById(this,
				"R.id.progressbar_loding");
		image_theme_title = (ImageView) ResFinder.findViewById(this,
				"R.id.image_theme_title");
		img_touxiang = (ImageView) ResFinder.findViewById(this,
				"R.id.img_touxiang");
		img_tiezi_tupian = (ImageView) ResFinder.findViewById(this,
				"R.id.img_tiezi_tupian");
		img_delete = (ImageView) ResFinder
				.findViewById(this, "R.id.img_delete");
		text_title = (TextView) ResFinder.findViewById(this, "R.id.text_title");
		text_theme_title = (TextView) findViewById(
				R.id.text_theme_title);
		text_tiezi_title = (TextView) ResFinder.findViewById(this,
				"R.id.text_tiezi_title");
		text_tiezi_context = (TextView) ResFinder.findViewById(this,
				"R.id.text_tiezi_context");
		if (fid == -1 || tid == -1) {
			imageLoader.displayImage(classSubMenu.getPicFile() + "",
					image_theme_title, options);
			stitle = classSubMenu.getName();
		} else {
			image_theme_title.setVisibility(View.GONE);
			text_title.setText("回帖");
            text_tiezi_title.setVisibility(View.GONE);

		}
		text_theme_title.setText(stitle);
	}

	// 初始化一些个人信息
	private void initUserInfo() {
		if (TzbCommonData.userInfoModel != null
				&& TzbCommonData.userInfoModel.isSuccess()) {
			imageLoader.displayImage(TzbCommonData.userInfoModel.getData()
					.getAvatar(), img_touxiang, options);
			return;
		}
		GalHttpRequest userInfoHttpRequest = new GalHttpRequest(this);
		userInfoHttpRequest.setCacheEnable(false);
		String url4 = ResFinder.getResString(this,
				"R.string.tzb_url_Tzb_UserInfoModel")
				+ "?username="
				+ TztData.userInfo.getData().getUserName();
		OutLog.LogE("yxw", "user:" + url4);
		userInfoHttpRequest.setURL(url4);
		userInfoHttpRequest
				.startAsynRequestString(new GalHttpLoadTextCallBack() {

					@Override
					public void textLoaded(String arg0) {
						Gson gson = new Gson();
						java.lang.reflect.Type type = new TypeToken<Tzb_UserInfoModel>() {
						}.getType();
						TzbCommonData.userInfoModel = gson.fromJson(arg0, type);
						removeProgressBar();
						if (TzbCommonData.userInfoModel.isSuccess()) {
							OutLog.LogE("yxw", "touxiang:"
									+ TzbCommonData.userInfoModel.getData()
											.getAvatar());
							imageLoader
									.displayImage(TzbCommonData.userInfoModel
											.getData().getAvatar(),
											img_touxiang, options);
						}
					}
				});

	}

	public void fabuTiezi(View v) {
		// showProgressBar();
		dialog.show();
		String url = "";
		if (fid == -1 || tid == -1) {
			url = ResFinder.getResString(this,
					"R.string.tzb_url_ForumthreadPub")
					+ "?fid="
					+ classSubMenu.getForumId()
					+ "&subject="
					+ text_tiezi_title.getText().toString()
					+ "&message="
					+ text_tiezi_context.getText().toString()
					+ "&sessionid="
					+ TztData.userInfo.getData().getSessionID();
		} else {
			url = ResFinder.getResString(this, "R.string.tzb_url_ForumpostPub")
					+ "?fid=" + fid + "&tid=" + tid + "&subject="
					+ text_tiezi_title.getText().toString() + "&message="
					+ text_tiezi_context.getText().toString() + "&sessionid="
					+ TztData.userInfo.getData().getSessionID();
		}

		OutLog.LogE("yxw", url);
		GalHttpRequest galHttpRequest = new GalHttpRequest(this);
		galHttpRequest.setCacheEnable(false);
		galHttpRequest.setURL(url);
		galHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

			@Override
			public void textLoaded(String arg0) {
				OutLog.LogE("yxw", "json:" + arg0);
				Gson gson = new Gson();
				java.lang.reflect.Type type = new TypeToken<DefaultResult>() {
				}.getType();
				result = gson.fromJson(arg0, type);
				if (result.isSuccess()) {
					pid = result.getMsg();
					if (fid == -1 || tid == -1) {
						Toast.makeText(TzbBangFatieActivity.this, "恭喜你，发帖成功！",
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(TzbBangFatieActivity.this, "恭喜你，回帖成功！",
								Toast.LENGTH_SHORT).show();
					}
					if (imagePath instanceof String) {
						Toast.makeText(TzbBangFatieActivity.this, "开始上传图片！",
								Toast.LENGTH_SHORT).show();
						new Thread(upLoadImageRun).start();
					} else {
						back();
						dialog.dismiss();
					}

				} else {
					Toast.makeText(TzbBangFatieActivity.this, "抱歉，发帖失败，请重试！", Toast.LENGTH_SHORT)
							.show();
				}
				// removeProgressBar();

			}
		});
	}

	private void back() {
		Intent intent = new Intent();
		intent.putExtra(TzbCommonData.IS_OK, true);
		setResult(1, intent);
		TzbBangFatieActivity.this.finish();
	}

	Runnable upLoadImageRun = new Runnable() {

		@Override
		public void run() {
			Message message = handler.obtainMessage();
			String url = ResFinder.getResString(TzbBangFatieActivity.this,
					"R.string.tzb_url_attachment_Add")
					+ "?sessionid="
					+ TztData.userInfo.getData().getSessionID() + "&pid=" + pid;
			OutLog.LogE("yxw", "add:" + url);
			String path = (String) imagePath;
			if (path != null) {
				String jsonString = HttpTools.uploadImage(url, path);
				Log.e("yxw", "jsonImage:" + jsonString);
				DefaultResult result = null;
				Gson gson = new Gson();
				java.lang.reflect.Type type = new TypeToken<DefaultResult>() {
				}.getType();
				result = gson.fromJson(jsonString, type);
				if (result.isSuccess()) {
					message.arg1 = 1;
				} else {
					message.arg1 = -1;
				}
			}
			handler.sendMessage(message);
		}
	};
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case 1:
				dialog.dismiss();
				Toast.makeText(TzbBangFatieActivity.this, "图片上传成功！",
						Toast.LENGTH_SHORT).show();
				back();
				break;
			case -1:
				dialog.dismiss();
				Toast.makeText(TzbBangFatieActivity.this, "图片上传失败！",
						Toast.LENGTH_SHORT).show();
				back();
				break;
			}
		}
	};

	private void deleteImage(Object object) {
		if (object instanceof String) {
			dialog.show();
			img_tiezi_tupian.setImageResource(R.drawable.tzb_image_add);
			img_delete.setVisibility(View.GONE);
			imagePath = null;
			Toast.makeText(TzbBangFatieActivity.this, "已删除图片！",
					Toast.LENGTH_SHORT).show();
			dialog.dismiss();
		} else {// 网络的删除需要通过HTTP请求
		}

	}

	// 删除图片
	public void onDeleteImage(View v) {
		new AlertDialog.Builder(TzbBangFatieActivity.this)
				.setTitle("友情提醒")
				.setMessage("您确定要删除这张照片吗？")
				.setPositiveButton("确	定",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								deleteImage(imagePath);
							}
						})
				.setNegativeButton("取	消",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
							}
						}).show();
	}

	// 显示选择相册or照片
	public void showAddImageDialog(View v) {
		if (!(imagePath instanceof DiaryPhoto)
				&& img_delete.getVisibility() != View.VISIBLE) {
			final CharSequence[] items = { "相册", "拍照", "取消" };

			dlg = new AlertDialog.Builder(this).setTitle("选择照片")
					.setItems(items, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							// 这里item是根据选择的方式，
							// 在items数组里面定义了两种方式，拍照的下标为1所以就调用拍照方法
							if (which == 0) {
								Intent getImage = new Intent(
										Intent.ACTION_GET_CONTENT);
								getImage.addCategory(Intent.CATEGORY_OPENABLE);
								getImage.setType("image/jpeg");
								startActivityForResult(getImage, 2);
							} else if (which == 1) {
								Intent getImageByCamera = new Intent(
										"android.media.action.IMAGE_CAPTURE");
								File tempFile = new File(FileConfig.IMAGE_PATH);
								if (!tempFile.isDirectory()) {
									tempFile.mkdirs();
								}
								FileConfig.IMAGE_NAME = FileConfig
										.getRandomJpgName();
								Uri imageUri = Uri.fromFile(new File(
										FileConfig.IMAGE_PATH,
										FileConfig.IMAGE_NAME));
								// 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
								getImageByCamera.putExtra(
										MediaStore.EXTRA_OUTPUT, imageUri);
								startActivityForResult(getImageByCamera, 3);
							} else {
								dlg.dismiss();
							}
						}
					}).create();
			dlg.show();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		BitmapFactory.Options option = null;
		switch (requestCode) {
		case 2:
			if (data != null) {
				img_delete.setVisibility(View.VISIBLE);
				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };

				Cursor cursor = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);
				cursor.close();
				// 图片的压缩显示，如果不压缩，当图片太大时会导致内存溢出 或者应用很卡
				option = new BitmapFactory.Options();
				option.inSampleSize = 5;
				imagePath = picturePath;
				img_tiezi_tupian.setImageBitmap(BitmapFactory.decodeFile(
						picturePath, option));
			}
			break;
		case 3:
			img_delete.setVisibility(View.VISIBLE);
			// 图片的压缩显示，如果不压缩，当图片太大时会导致内存溢出 或者应用很卡
			option = new BitmapFactory.Options();
			String path = FileConfig.IMAGE_PATH + "/" + FileConfig.IMAGE_NAME;
			option.inSampleSize = 5;
			imagePath = path;
			img_tiezi_tupian.setImageBitmap(BitmapFactory.decodeFile(path,
					option));
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
